package handler

import (
	"github.com/gin-gonic/gin"
	"role-mgr/models"
	"strconv"
)

func UserRoleAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("uid"))
	uid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))

	data := models.RoleNode{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleList(c *gin.Context) {

	uid, _ := strconv.Atoi(c.Query("uid"))
	var news []models.Role
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		  WHERE user_roles.uid=1
	*/
	models.DB.Table("roles").
		Joins(" LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid =?", uid).
		Debug().
		Find(&news)
	c.JSON(200, gin.H{
		"code": 200,
		"data": news,
		"msg":  "查询成功",
	})
	return

}

func NodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var news []models.Node
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.rid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	models.DB.Table("nodes").
		Joins(" LEFT JOIN role_nodes ON role_nodes.rid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Debug().
		Find(&news)
	c.JSON(200, gin.H{
		"code": 200,
		"data": news,
		"msg":  "查询成功",
	})
	return

}
